<template>
  <div>
    <a-modal :width="850" :title="state === 1 ? '选择员工' : '添加参保'" :visible="show" @cancel="cancel">
      <template slot="footer">
        <a-button @click="cancel"> 取消 </a-button>
        <a-button key="submit" type="primary" @click="ok">
          {{ state === 1 ? "确定" : "下一步" }}
        </a-button>
      </template>
      <a-spin :spinning="spinning">
        <div class="employee-selector-wrapper2">
          <div>
            <div class="employee-selector-block">
              <a-input-search
                :placeholder="state === 1 ? '输入姓名或身份证号搜索员工' : '输入姓名或手机号搜索员工'"
                style="width: 100%"
                @search="searchPeople"
                @change="changePeople"
              />
            </div>
            <a-tabs default-active-key="1" @change="onChangeTab" style="margin-bottom: 10px; width: 450px" size="small" :tabBarGutter="3">
              <a-tab-pane key="1" tab="全部待添">
                <div class="postTypeL">
                  <div
                    v-for="(item, i) in postTypeList"
                    :key="i"
                    :class="postTypeValue === item.value ? 'primary_bg' : 'bg_F0'"
                    :style="[
                      { width: '70px' },
                      { height: '25px' },
                      {
                        color: postTypeValue === item.value ? '#fff' : '#55565D'
                      },
                      { borderRadius: '12px 12px 12px 12px' },
                      { lineHeight: '25px' },
                      { textAlign: 'center' },
                      { marginRight: '8px' },
                      { fontSize: '12px' },
                      { cursor: 'pointer' }
                    ]"
                    @click="postTypeClick(item.value)"
                  >
                    {{ item.title }}
                  </div>
                </div>
                <div class="tree-item2">
                  <div>全选当页</div>
                  <img />
                  <i
                    v-if="isAllSelected"
                    @click="choseAll(treeData)"
                    style="font-size: 19px"
                    class="iconfont icon-check-circle-fill primary_color"
                  >
                  </i>
                  <img
                    v-else
                    @click="choseAll(treeData)"
                    src="@/assets/icons/未选择.png"
                    style="width: 18px; height: 18px; margin-left: 10px"
                  />
                </div>
                <div class="employee-selector">
                  <div v-for="(item, index) in treeData" :key="index" class="mg_t10">
                    <div class="tree-item" @click="chose(item, treeData)">
                      <span>
                        <img src="@/assets/icons/person1.png" style="width: 30px; height: 30px; margin-right: 10px" />
                        {{ item.name }}
                        {{ item.phone ? "(" + item.phone + ")" : "" }}
                      </span>

                      <img />
                      <i
                        v-if="item.isSelected"
                        v-on:click.stop="chose(item, treeData)"
                        style="font-size: 19px"
                        class="iconfont icon-check-circle-fill primary_color"
                      >
                      </i>
                      <img
                        v-else
                        v-on:click.stop="chose(item, treeData)"
                        src="@/assets/icons/未选择.png"
                        style="width: 18px; height: 18px"
                      />
                    </div>
                  </div>
                </div>
                <a-pagination
                  v-model="current"
                  :page-size-options="pageSizeOptions"
                  :total="total"
                  show-size-changer
                  show-less-items
                  :page-size="pageSize"
                  @showSizeChange="onShowSizeChange"
                  @change="onPageChange"
                >
                  <template slot="buildOptionText" slot-scope="props">
                    <span>{{ props.value }}条/页</span>
                  </template>
                </a-pagination>
              </a-tab-pane>
            </a-tabs>
          </div>
          <div class="verticalBar" />

          <div class="employee-selector-block2">
            <div class="employee-selector-title">已经选择人员 {{ selectedListTemp.length }}人</div>
            <div class="employee-selector">
              <div v-for="(item, i) in selectedListTemp" :key="i" class="employee-selector-item">
                <div>
                  <img src="@/assets/icons/person1.png" style="width: 30px; height: 30px; margin-right: 10px" />
                  {{ item.name }}
                </div>
                <img @click="deleteItem(item)" src="@/assets/icons/删除.png" style="width: 20px; height: 20px" />
              </div>
            </div>
          </div>
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import { getDepEmpInfo2, getRecordInfo } from "@/api/company/contract";
import { addBatchRecord } from "@/api/shebao/shebaoInfo.js";
export default {
  props: {
    state: {
      type: Number,
      default: 0
    },
    year: {
      type: String,
      default: ""
    },
    month: {
      type: String,
      default: ""
    },
    show: {
      type: Boolean,
      default: false
    },
    number: {
      type: Number,
      default: 0
    },
    templateId: {
      type: Number,
      default: 0
    },
    defaultSelectedKeys: {
      type: Array,
      default: () => []
    },
    isOnlineOrLeave: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      recordList: [],
      spinning: false,
      mode: "1",
      treeData: [],
      selectedListTemp: [],
      isAllSelected: false,
      selectedKeysBeforeSearch: [],
      postTypeValue: 3,

      pageSizeOptions: ["10", "20", "50", "100"],
      pageSize: 10,
      current: 1,
      total: 50
    };
  },
  computed: {
    postTypeList() {
      return this.$store.state.enums.postTypeLst;
    }
  },
  watch: {
    show(val) {
      if (val) {
        console.log(this.state);
        this.selectedListTemp = [];
        this.treeData = [];
        this.spinning = false;
        this.current = 1;
        this.postTypeValue = 3;
        this.mode = "1";
        if (this.defaultSelectedKeys.length !== this.selectedListTemp.length || this.defaultSelectedKeys.length === 0) {
          this.getSelectDepTree();
        }
      }
    },

    month(val) {}
  },
  mounted() {},
  methods: {
    // 分页变化
    onPageChange(pageNumber) {
      this.current = pageNumber;
      this.getSelectDepTree();
    },
    postTypeClick(value) {
      this.postTypeValue = value;
      this.isAllSelected = false;
      this.current = 1;
      this.getSelectDepTree();
    },
    onShowSizeChange(current, pageSize) {
      this.pageSize = pageSize;
      this.current = 1;
      this.getSelectDepTree();
    },
    choseAll(data) {
      this.isAllSelected = !this.isAllSelected;
      var that = this;
      this.spinning = true;
      for (var j = 0, len = data.length; j < len; j++) {
        data[j].isSelected = that.isAllSelected;
        that.ergodicAll(data[j]);
      }

      setTimeout(function () {
        that.spinning = false;
      }, "10");
    },
    chose(item, data) {
      item.isSelected = !item.isSelected;
      this.onChange(item);
    },
    onChangeTab(e) {
      this.isAllSelected = false;
      this.current = 1;
      this.mode = e;
      this.getSelectDepTree();
    },
    onChange(item) {
      this.spinning = true;
      var that = this;
      setTimeout(function () {
        that.ergodic(item);
        that.spinning = false;
      }, "10");
    },
    ergodic(item) {
      if (!item.isSelected) {
        var index = this.selectedListTemp.findIndex((it) => it.id === item.id); // 存在再删除，防止删除错误
        if (index !== -1) {
          this.selectedListTemp.splice(index, 1); // 删除
          this.isAllSelected = false;
        }
      } else {
        if (this.selectedListTemp.findIndex((it) => it.id === item.id) === -1) {
          // 不存在再添加，防止重复添加
          this.selectedListTemp.push(item);

          var count = this.treeData.length;
          var allSelect = true;
          for (var i = 0; i < count; i++) {
            if (!this.treeData[i].isSelected) {
              allSelect = false;
              break;
            }
          }
          this.isAllSelected = allSelect;
        }
      }
    },
    ergodicAll(item) {
      if (!item.isSelected) {
        var index = this.selectedListTemp.findIndex((it) => it.id === item.id); // 存在再删除，防止删除错误
        if (index !== -1) {
          this.selectedListTemp.splice(index, 1); // 删除
        }
      } else {
        if (this.selectedListTemp.findIndex((it) => it.id === item.id) === -1) {
          // 不存在再添加，防止重复添加
          this.selectedListTemp.push(item);
        }
      }
    },

    // 获取部门树
    getSelectDepTree(query) {
      if (query) {
        this.current = 1;
      }
      const params = {
        companyId: this.$store.state.hr.companyId,
        year: this.year,
        month: this.month,
        pageNo: this.current,
        pageSize: this.pageSize,
        postType: this.postTypeValue + ""
      };
      if (query && this.state === 1) {
        params["name"] = query;
      } else {
        params["nameOrPhone"] = query;
      }

      this.spinning = true;
      if (this.state === 1) {
        getRecordInfo(params)
          .then((res) => {
            if (res.data.entities === null) {
              this.$message.success("暂无数据");

              res.data.entityCount = [];
              this.treeData = [];
              this.total = 0;
              this.isAllSelected = false;
            } else {
              this.treeData = this.formatCompanyData(res.data.entities);
              this.total = res.data.entityCount;
              var count = this.treeData.length;
              var allSelect = true;
              if (count !== 0) {
                for (var i = 0; i < count; i++) {
                  if (!this.treeData[i].isSelected) {
                    allSelect = false;
                    break;
                  }
                }

                this.isAllSelected = allSelect;
              } else {
                this.isAllSelected = false;
              }
            }

            this.$nextTick(() => {
              this.spinning = false;
            });
          })
          .catch((err) => {
            console.log("debug log --> ", err);
          });
      } else {
        getDepEmpInfo2(params)
          .then((res) => {
            if (res.data.entities === null) {
              this.$message.success("暂无数据");

              res.data.entityCount = [];
              this.treeData = [];
              this.total = 0;
              this.isAllSelected = false;
            } else {
              this.treeData = this.formatCompanyData(res.data.entities);
              this.total = res.data.entityCount;
              var count = this.treeData.length;
              var allSelect = true;
              if (count !== 0) {
                for (var i = 0; i < count; i++) {
                  if (!this.treeData[i].isSelected) {
                    allSelect = false;
                    break;
                  }
                }

                this.isAllSelected = allSelect;
              } else {
                this.isAllSelected = false;
              }
            }

            this.$nextTick(() => {
              this.spinning = false;
            });
          })
          .catch((err) => {
            console.log("debug log --> ", err);
          });
      }
    },
    formatCompanyData(company) {
      const parent = [];
      for (var key = 0; key < company.length; key++) {
        var selected = false;
        if (this.selectedListTemp.findIndex((it) => it.id === company[key].id) !== -1) {
          selected = true;
        }
        if (this.selectedListTemp.findIndex((it) => it.id === company[key].empId) !== -1) {
          selected = true;
        }
        var emp = {};
        if (this.state === 1) {
          emp = company[key];
          emp.id = emp.empId;
          emp.isSelected = selected;
          parent.push(emp);
        } else {
          emp = {
            id: company[key].id,
            name: company[key].name,
            phone: company[key].phone,
            idCard: company[key].idCard,
            depName: company[key].depName,
            positionName: company[key].positionName,
            isSelected: selected
          };
          parent.push(emp);
        }
      }
      return parent;
    },
    searchPeople(query) {
      this.selectedKeysBeforeSearch = this.selectedListTemp.map((item) => item.id);
      this.getSelectDepTree(query);
    },
    changePeople(e) {
      if (e.target.value === "") {
        this.getSelectDepTree();
        this.selectedKeysBeforeSearch = this.selectedListTemp.map((item) => item.id);
      }
    },
    deleteItem(item) {
      item.isSelected = false;
      this.spinning = true;
      var that = this;
      setTimeout(function () {
        that.ergodic(item);
        that.spinning = false;
      }, "10");
    },
    ok() {
      if (this.selectedListTemp.length === 0) {
        this.$message.success("请选择人员");
        return;
      }
      if (this.state === 1) {
        this.recordList = [];

        this.selectedListTemp.forEach((item, index) => {
          this.recordList.push({
            remark: item.remark,
            companyId: this.$store.state.hr.companyId,
            empId: item.empId,
            // empSocInfoId: item.id,
            year: this.year,
            month: this.month,
            serviceCost: item.serviceCost,
            socAmount: item.personalSocAmount + item.companySocAmount + item.personalPfAmount + item.companyPfAmount,
            overdueFine: item.accumulationFundFine + item.socialSecurityFine
          });
        });
        addBatchRecord(this.recordList).then((res) => {
          this.$emit("update:show", false);
          this.$notification["success"]({
            message: "success",
            description: "计划生成成功"
          });
        });
      } else {
        this.$emit("update:selectedList", this.selectedListTemp);
        this.$emit(
          "update:selectThree",
          this.selectedListTemp
            .slice(0, 3)
            .map((item) => item.name)
            .join(",")
        );
        this.$emit("update:show", false);
        this.$emit("change", this.selectedListTemp);
      }
    },
    cancel() {
      this.$emit("update:show", false);
    }
  }
};
</script>
<style lang="scss" scoped>
.postTypeL {
  display: flex;

  flex-direction: row;
  align-items: center;
}
.employee-selector {
  height: 360px;
  margin-top: 2px;
  padding-right: 10px;
  margin-bottom: 10px;
  overflow: auto;
}
.active {
  background-color: var(--primary);
}
.active1 {
  background-color: #f0f0f0;
}
.verticalBar {
  width: 1px;

  background: #e8e8e8;
  display: inline-block;
  margin-top: 40px;
  vertical-align: top;
  margin-right: 30px;
  margin-left: 30px;
  html,
  body,
  #app {
    height: 100%;
  }
}
.tree-item {
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  align-items: center;
  cursor: pointer;
  margin-top: 10px;
}
.tree-item2 {
  display: flex;
  flex-direction: row;
  align-items: center;
  cursor: pointer;
  margin-top: 10px;
  margin-bottom: 10px;
}
.employee-selector-wrapper2 {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  .employee-selector-block {
    width: 400px;
    .employee-selector-title {
      width: 100%;
      height: 32px;
      line-height: 32px;
      font-size: 14px;
    }
    .employee-selector {
      height: 400px;
      margin-top: 20px;
      padding-right: 20px;
      overflow: auto;
      .employee-selector-item {
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
      }
    }
  }
  .employee-selector-block2 {
    width: 400px;
    .employee-selector-title {
      width: 100%;
      height: 32px;
      line-height: 32px;
      font-size: 14px;
    }
    .employee-selector {
      height: 500px;
      margin-top: 20px;
      padding-right: 10px;
      overflow: auto;
      .employee-selector-item {
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
      }
    }
  }
}
</style>
